const query = require('../../dbConfig/index')

const get = async (ctx,next)=>{
	const body = ctx.request.body
	const offset = (body.pageNumber - 1) * Number(body.pageSize);  
	let sql = 'SELECT * FROM course';  
	let params = [];  
	// 如果传了条件 就拼接sql
	if (body.speciality) {  
		sql += ' WHERE specialty=?';  
		params.push(body.speciality);  
	  }  
	  sql += ' LIMIT ? OFFSET ?';  
	  params.push(Number(body.pageSize));  
	  params.push(offset);
	const res = await query(sql,params)
	const total = await query(`SELECT COUNT(*) as total FROM course`)
	if(res.length>0){
		ctx.body={code:200,data:{records:res,total:total[0].total},msg:'成功'}
		next()
	}else{
		ctx.body={code:0,data:null,msg:'暂无科目数据'}
	}
}
const updata = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`UPDATE course SET course_name = ?,specialty=?,course_isuse=?,course_icon=?,class_hour=?,course_desc=? WHERE course_id='${body.courseId}'`,[body.courseName,body.specialty,body.courseIsuse,body.courseIcon,body.classHour,body.courseDesc])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
	
}
const add = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`INSERT INTO course (course_name,specialty,course_isuse,course_icon,class_hour,course_desc) VALUES (?,?,?,?,?,?)`,[body.courseName,body.specialty,body.courseIsuse,body.courseIcon,body.classHour,body.courseDesc])
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
const remove = async (ctx,next)=>{
	const body = ctx.request.body
	await query(`DELETE FROM course WHERE course_id=${body.id}`)
	ctx.body={code:200,data:null,msg:'成功'}
	next()
}
module.exports = {
	get,
	add,updata,remove
}